package com.demo.paypalmanagement.service;


import com.demo.paypalmanagement.model.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class SecurityUserService implements UserDetailsService {

  @Autowired
  private IUsersService iUserService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    Users users =null;
    // 假设可以通过某种方式判断identifier是用户名还是邮箱
    if (username.contains("@")) { // 简单的邮箱检测
      users = this.iUserService.getUserByEmail(username);
    } else {
      users = this.iUserService.getUserByUsername(username);
    }

    if (users == null) {
      throw new UsernameNotFoundException("用户未找到: " + username);
    }

    // 获取用户的角色列表
    List<GrantedAuthority> authorities = new ArrayList<>();
    if ("1".equals(users.getUserRole())) {
      authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
    } else {
      authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
    }

    // 创建 UserDetails 对象
    UserDetails userDetails = new User(
            users.getAccount(),
            users.getPassword(),
            authorities
    );
    return userDetails;
  }
}